package com.jvtd.baseProject.di.module;


import android.app.Application;
import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jvtd.baseProject.di.ApplicationContext;

import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/10/16.
 * 网络
 */
@Module
public class NetModule
{
  private String mBaseUrl;
  private Application mApplication;

  public NetModule(String baseUrl, Application application)
  {
    mBaseUrl = baseUrl;
    mApplication = application;
  }

  @Provides
  @ApplicationContext
  Context provideContext()
  {
    return mApplication;
  }

  @Provides
  Application provideApplication()
  {
    return mApplication;
  }

  @Provides
  @Singleton
  Cache provideCache()
  {
    int cacheSize = 10 * 1024 * 1024;
    return new Cache(mApplication.getCacheDir(), cacheSize);
  }

  @Provides
  @Singleton
  Gson provideGson()
  {
    GsonBuilder builder = new GsonBuilder();
    return builder.create();
  }

  @Provides
  @Singleton
  HttpLoggingInterceptor provideHttpLoggingInterceptor()
  {
    HttpLoggingInterceptor httpLog = new HttpLoggingInterceptor();
    httpLog.setLevel(HttpLoggingInterceptor.Level.BODY);
    return httpLog;
  }

  @Provides
  @Singleton
  OkHttpClient provideOkHttpClient(Cache cache, HttpLoggingInterceptor interceptor)
  {
    return new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(interceptor)
//            .addInterceptor(new JvtdTokenInterceptor(JvtdRxSchedulers.CODE_NEED_LOGIN, new JvtdTokenInterceptor.OnTokenListener() {
//              @Override
//              public String getNewToken() {
//                return "";
//              }
//            }))
            .cache(cache)
            .build();
  }

  @Provides
  @Singleton
  Retrofit provideRetrofit(Gson gson, OkHttpClient client)
  {
    return new Retrofit.Builder()
            .client(client)
            .baseUrl(mBaseUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
  }


}
